<?php
declare (strict_types = 1);

namespace app\service\logic\common\course;

use app\model\communal\CourseModel;
use app\service\logic\BaseService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

final class CourseService extends BaseService
{
    protected string $modelClassName = 'CourseModel';

    /**
     * 排序参数
     *
     * @param $params
     * @param string $column
     * @param string $type
     * @return array|string[]
     */
    public function orderByParams($params, string $column = 'id', string $type = 'desc')
    {
        if (
            isset($params['order_option']) &&
            in_array($params['order_option'], [1,2,3,4,5])
        ) {
            $orderField = CourseModel::$orderRuleMap[$params['order_option']]['orderBy'];
            $orderDir = CourseModel::$orderRuleMap[$params['order_option']]['orderDir'];
            $order = [$orderField => $orderDir, 'id' => 'desc'];
            unset($params['order_option']);
        } else {
            $orderField =  isset($params['orderBy']) && !empty($params['orderBy']) ? $params['orderBy'] : $column;
            $orderDir =  isset($params['orderDir']) && !empty($params['orderDir']) ? $params['orderDir'] : $type;
            $order = [$orderField => $orderDir];
        }

        return $order;
    }

    /**
     * 课程章节视频数据拼装
     *
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function buildChapterSectionVideo($id)
    {
        $model = CourseModel::findOrFail($id);
        $result['version'] = '1';
        $result['name'] = $model['name'];
        // 获取章, 节, 视频
        $chapters = $model->manyChapters;
        if (!$chapters->isEmpty()) {
            // 存在章
            $tempChapters = [];
            foreach ($chapters as $chapter) {
                $tempChapter['chapter_name'] = $chapter['name'];
                $sections = $chapter->manySections;
                if (!$sections->isEmpty()) {
                    // 存在节
                    $tempSections = [];
                    foreach ($sections as $section) {
                        $video = $section->hasVideo;
                        $tempSection = [
                            'id' => $section['id'],
                            'name' => $section['name'],
                            'video_name' => empty($video) ? '' : $video['name'],
                            'video_url' => empty($video) ? '' : $video['video'],
                        ];
                        $tempSections[] = $tempSection;
                    }
                    $tempChapter['sections'] = $tempSections;
                } else {
                    $tempChapter['sections'] = [];
                }
                $tempChapters[] = $tempChapter;
            }
            $result['chapters'] = $tempChapters;
        } else {
            $result['chapters'] = [];
        }

        return $result;
    }
}
